<template>
  <h1>水果列表</h1>
  <form @submit.prevent="sbmt">
    <div>
      <label for="fname">名称:</label>
      <input
        type="text"
        id="fname"
        v-model="name"
        placeholder="请输入水果名称"
        required
      />
    </div>
    <div>
      <label for="fprice">价格:</label>
      <input
        type="text"
        id="fprice"
        v-model="price"
        placeholder="请输入水果价格"
        required
      />
    </div>
    <br />
    <button type="submit">提交</button>
  </form>
  <ul>
    <li v-for="(item, index) in list" :key="index">
      名称:{{ item.name }}, 价格:{{ item.price }}, 数量:
      <button @click="sub(index)">-</button>
      <span>{{ item.count }}</span>
      <button @click="add(index)">+</button>
    </li>
  </ul>
  <h1>总价:{{ totalPrice }}</h1>
</template>


<script>
import { ref, reactive } from "@vue/reactivity";
import { computed } from "@vue/runtime-core";
export default {
  setup() {
    const name = ref("");
    const price = ref("");
    const list = reactive([]);
    const totalPrice = computed(() => {
      var sum = 0;
      list.forEach((item) => {
        sum += item.price * item.count;
      });
      return sum;
    });

    function sbmt() {
      const fruits = reactive({
        name: name.value,
        price: price.value,
        count: 1,
      });
      list.push(fruits);
      name.value = "";
      price.value = "";
    }

    function sub(index) {
      if (list[index].count > 0) {
        list[index].count--;
      } else if (confirm("您确定要删除吗?")) {
        list.splice(index, 1);
      }
    }
    function add(index) {
      if (list[index].count < 100) {
        list[index].count++;
      } else {
        alert("单个最多只能购买100个哦");
      }
    }

    return {
      name,
      price,
      list,
      sbmt,
      totalPrice,
      sub,
      add,
    };
  },
};
</script>